<template>
	<el-row :gutter="20">
	    <el-col :span="12" :offset="6">
	      <el-form
	          ref="ruleFormRef"
	          style="max-width: 600px"
	          :model="ruleForm"
	          status-icon
	          :rules="rules"
	          label-width="auto"
	          class="demo-ruleForm"
	        >
			  <el-form-item label="用户名" prop="username">
				<!-- 用户名输入框失焦时 会重新根据最新的用户名生成新的验证码 -->
				<el-input v-model="ruleForm.username" type="text" @blur="getVerifyCode"
				  autocomplete="off" style="width: 380px;height:40px"/>
			  </el-form-item>
	          <el-form-item label="密码" prop="password">
	            <el-input v-model="ruleForm.password" type="password" autocomplete="off" style="width: 380px;height:40px"/>
	          </el-form-item>
			  <el-form-item label="验证码" prop="verifycode">
				<el-image :src="base64str" @click="getVerifyCode"/>
				<el-input v-model="ruleForm.verifycode" type="text" style="width: 240px;height:40px" autocomplete="off" />
	          </el-form-item>
	          <el-form-item>
	            <el-button type="primary" @click="submitForm">登录</el-button>
	            <el-button @click="resetForm">重置</el-button>
	          </el-form-item>
	        </el-form>
	    </el-col>
	  </el-row>
</template>

<script setup>
import httpRequest from '@/common';
import { ElMessage } from 'element-plus';
import { reactive, ref , getCurrentInstance, onMounted, watch} from 'vue'
import { FormInstance, FormRules } from 'element-plus'

	//获取当前实例   方便发送axios请求
    let {proxy} = getCurrentInstance();

    //通过ref属性值来获取Form元素
	const ruleFormRef = ref(null);

	const ruleForm = ref({
	  username: 'admin',
	  password: '123456',
	  verifycode: ''
	})

	//验证码的校验
	const validateCode = (rule, value, callback) => {
		if (value === '') {
			callback(new Error('请输入验证码'))
		} else if (value.length!=4) {
			callback(new Error("验证码必须是4位"))
		} else {
			proxy.$axios.get('/verifyCode/valide/'+ruleForm.value.username+'/'+value)
						.then(res=>{
							if(res.data.code == 200){
								// ElMessage.success('验证成功');
								callback();
							}else{
								ElMessage.error(res.data.msg);
								callback(new Error(res.data.msg));
							}
						})
			
		}
	}

    //表单校验规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 4, message: '用户名不能小于4位', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
	  verifycode: [
		// {required: true, message: '请输入验证码', trigger: 'blur'},
		// { min: 4, max: 4, message: '验证码必须是4位', trigger: 'blur' }
		{ validator: validateCode, trigger: 'blur' }
	  ]
    }
	
	//点击登录调用
	const submitForm = () => {
		  //校验表单
	      ruleFormRef.value.validate((valid) => {
	        if (valid) {
				console.log('发送登录请求!')
				//校验成功  发送登录请求
				  proxy.$axios({
					  method: 'post',
					  url: '/log/in',
					  data: ruleForm.value
				  }).then(res=>{
					  let resultBean = res.data;
					  if(resultBean.code == 200){
						  //将登录成功的用户名存入本地存储
						  let jsonStr = JSON.stringify(resultBean.data);
						  console.log('------jsonStr-------',jsonStr);
						  window.localStorage.setItem("adminUser",jsonStr); //存的是登录成功的员工信息
						  window.localStorage.setItem("token",resultBean.msg); //存的是token
						  //路由跳转到主页面
						  proxy.$router.push("/main");
					  }else{
						  ElMessage.error(resultBean.msg);
					  }
				  })
	        } else {
				ElMessage.error('登录失败');
	          return false
	        }
	      })
	    }
	
	    //表单重置
	    const resetForm = () => {
			ruleForm.value = {
				username: '',
	  			password: '',
				verifyCode:''
			}
	      ruleFormRef.value.resetFields()
	    }





//获取的验证码图片的base64
const base64str = ref('');

//获取验证码
const getVerifyCode = ()=>{

	if(!ruleForm.value.username){
		httpRequest(
		proxy,
		'get',
		'/verifyCode/image/'+'ruleForm.value.username',
		null,
		resultBean=>{
		   base64str.value = resultBean.data;
		}
		)
		return;
	}

	httpRequest(
		proxy,
		'get',
		'/verifyCode/image/'+ruleForm.value.username,
		null,
		resultBean=>{
		   base64str.value = resultBean.data;
		}
	)
}

onMounted(()=>{
	//生成验证码
	getVerifyCode();
})

</script>

<style scoped>
	.el-row {
	  margin-top: 200px;
	}
</style>